package com.nageoffer.shortlink.admin.test;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    private final int num = 0;
    private static ReentrantLock lock = new ReentrantLock(true);
    public static class T extends Thread {
        public T(String name) {
            super(name);
        }
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }finally {
                    lock.unlock();
                }
            }
        }
    }

    public void TRun(){
        T t1 = new T("t1");
        T t2 = new T("t2");
        T t3 = new T("t3");
        t1.start();
        t2.start();
        t3.start();
    }

    public static void CAS(){
        AtomicInteger atomicInteger = new AtomicInteger(100);
        class T extends Thread {
            public T(String name) {
                super(name);
            }
            @Override
            public void run() {
                int oriValue;
                int newValue;
                do {
                    oriValue = atomicInteger.get();
                    newValue = atomicInteger.get()-1;
                }while (!atomicInteger.compareAndSet(oriValue, newValue));
                System.out.println(Thread.currentThread().getName() + "修改成功:"+atomicInteger.get());
            }
        }
        new T("t1").start();
        new T("t2").start();
        new T("t3").start();
    }

    public static void main(String[] args) throws InterruptedException {
        CAS();
    }
}
